package com.santiao.fuel.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;


import com.google.android.material.tabs.TabLayout;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.impl.BottomListPopupView;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.santiao.fuel.R;
import com.santiao.fuel.bean.UnitBean;
import com.santiao.fuel.databinding.FragmentCalculatorBinding;
import com.santiao.fuel.databinding.UnitSelectInnerBinding;
import com.santiao.fuel.ui.adapter.GasUnitSelectorAdapter;
import com.santiao.fuel.utils.DisplayUtil;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


interface IUnitQueryCallBack {
    void queryResult(String ans, String text);
}

public class CalculatorFragment extends Fragment implements IUnitQueryCallBack {
    FragmentCalculatorBinding binding;

    CalculatorViewModel viewModel;

    String groupingSeparatorSymbol = ",";
    String decimalSeparatorSymbol = ".";


    // 当前选中的tab标签
    private String currentTab = "";


    //维护 所有单位的集合
    public static Map<String, List<UnitBean>> units = new HashMap<>();



    public static List<String> tabs = new ArrayList<>();

    static {


        // 长度换算单位
        List<UnitBean> lengthBeans = new ArrayList<>();
        // 速度单位

        List<UnitBean> speedsUnitBeans = new ArrayList<>();
        // 体积单位

        List<UnitBean> capacity = new ArrayList<>();

        // 时间单位
        List<UnitBean> timeUnit = new ArrayList<>();

        List<UnitBean> weights = new ArrayList<>();
        Collections.addAll(lengthBeans,
                new UnitBean("千米", "km") ,
                new UnitBean("米", "m"),
                new UnitBean("分米", "dm"),
                new UnitBean("厘米", "cm"),
                new UnitBean("毫米", "mm"),
                new UnitBean("丝米", "dmm"),
                new UnitBean("微米", "um"),
                new UnitBean("纳米", "nm"),
                new UnitBean("皮米", "pm"),
                new UnitBean("里", null),
                new UnitBean("丈", null),
                new UnitBean("尺", null),
                new UnitBean("寸", null),
                new UnitBean("分", null),
                new UnitBean("厘", null),
                new UnitBean("毫", null),
                new UnitBean("英里", "mi"),
                new UnitBean("英尺", "ft"),
                new UnitBean("英寸", "in"),
                new UnitBean("海里", "nmi"));
        Collections.addAll(capacity,
                new UnitBean("立方米", "m³"),
                new UnitBean("立方分米/升", "m³/l"),
                new UnitBean("公石", "hl"),
                new UnitBean("十升", "dal"),
                new UnitBean("分升", "dl"),
                new UnitBean("厘升", "cl"),
                new UnitBean("立方厘米/毫升", "cm³/ml"),
                new UnitBean("立方毫米", "mm³")
                );

        Collections.addAll(speedsUnitBeans,
                new UnitBean("千米/小时", "km/h"),
                new UnitBean("米/秒", "m/s") ,
                new UnitBean("千米/秒", "km/s"),
                new UnitBean("光速", "c"),
                new UnitBean("马赫", "mach"),
                new UnitBean("英里/时", "mile/h"),
                new UnitBean("英寸/秒", "in/s"));

        Collections.addAll(timeUnit,
                new UnitBean("年", "y"),
                new UnitBean("季度", null),
                new UnitBean("月", "m"),
                new UnitBean("周", "w"),
                new UnitBean("天", "d"),
                new UnitBean("小时", "h"),
                new UnitBean("分钟", "min"),
                new UnitBean("秒", "s"),
                new UnitBean("毫秒", "ms"),
                new UnitBean("微秒", "μs"),
                new UnitBean("纳秒", "ns")
                );

//        Collections.addAll(weights, "公斤", "克", "毫克", "微克", "公担", "克拉", "分", "斤/市斤", "担", "两", "钱"
//                , "金衡磅" , "金衡盎司" , "英钱" , "金衡格令", "英制长吨" , "英制短吨" , "英担" , "美担" , "英石" , "盎司" , "打兰","格令");


        Collections.addAll(weights ,
                new UnitBean("公斤", "kg") ,
                new UnitBean("吨", "t") ,
                new UnitBean("克", "g") ,
                new UnitBean("毫克", "mg") ,
                new UnitBean("微克", "μg") ,
                new UnitBean("公担", null) ,
                new UnitBean("克拉", "ct") ,
                new UnitBean("分", null) ,
                new UnitBean("斤/市斤", null) ,
                new UnitBean("担", null) ,
                new UnitBean("两", null) ,
                new UnitBean("钱", null) ,
                new UnitBean("金衡磅", null) ,
                new UnitBean("金衡盎司", null) ,
                new UnitBean("英钱", "dwt") ,
                new UnitBean("金衡格令", null) ,
                new UnitBean("英制长吨", null) ,
                new UnitBean("英制短吨", null) ,
                new UnitBean("英担", null) ,
                new UnitBean("美担", null) ,
                new UnitBean("英石", null) ,
                new UnitBean("磅", "lb") ,
                new UnitBean("盎司", "oz") ,
                new UnitBean("打兰", "dr") ,
                new UnitBean("格令", "gr")
                );
        // 使用hashmap映射
        units.put("长度换算", lengthBeans);
        units.put("体积换算", capacity);
        units.put("速度换算", speedsUnitBeans);
        units.put("时间换算", timeUnit);
        units.put("重量换算" , weights);


    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentCalculatorBinding.inflate(inflater, container, false);
        viewModel = new ViewModelProvider(this).get(CalculatorViewModel.class);
        binding.setLifecycleOwner(this);
        binding.setCam(viewModel);
        viewModel.setBinding(binding);
        observer();
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        binding.pointButton.setImageResource(R.drawable.dot);
        super.onViewCreated(view, savedInstanceState);
        // 获取状态栏高度的资源 ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        binding.slidingLayout.setGravity(Gravity.BOTTOM);

        // 如果资源 ID 有效，则获取状态栏高度
        if (resourceId > 0) {
            int statusBarHeight = getResources().getDimensionPixelSize(resourceId);
//            binding.topBackground.getLayoutParams().height=statusBarHeight;
        } else {
            Log.d("StatusBarHeight", "无法获取状态栏高度");
        }
        binding.gasBar.pageTitle.setText("单位换算");
        binding.gasBar.pageBack.setVisibility(View.GONE);

        settingZero();
        initTabBar();

        initSelectUnit();

        DisplayUtil.initActionBar(requireActivity());


    }

    public static boolean acIsClick = false;


    /**
     * 设置输入框 和 结果回显文本 为0
     */
    private void settingZero() {


        // 设置输入框 和 显示框 归0
        binding.input.setText("0");
        binding.resultDisplay.setText("0");
    }

    @SuppressLint("NewApi")
    private void initSelectUnit() {

        binding.tabWrapper.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 选中
                currentTab = tab.getText().toString();


                switch (currentTab) {
                    case "长度换算":
                        binding.preUnit.setText("千米");
                        binding.ansUnit.setText("米");

                        binding.ansUnitEnd.setText("m");
                        binding.preUnitEnd.setText("km");
                        break;
                    case "体积换算":
                        binding.preUnit.setText("立方米");
                        binding.ansUnit.setText("立方米/升");


                        binding.ansUnitEnd.setText("m³");
                        binding.preUnitEnd.setText("dm³/l");
                        break;
                    case "速度换算":

                        // ============= 换算前的单位设置 前后两个 =========================//
                        binding.preUnit.setText("米/秒");
                        binding.preUnitEnd.setText("m/s");

                        // ============= 换算后的单位设置 前后两个 =========================//
                        binding.ansUnit.setText("千米/秒");
                        binding.ansUnitEnd.setText("km/s");
                        break;
                    case "时间换算":
                        // ============= 换算前的单位设置 前后两个 =========================//
                        binding.preUnit.setText("年");
                        binding.preUnitEnd.setText("y");

                        // ============= 换算后的单位设置 前后两个 =========================//
                        binding.ansUnit.setText("季度");
                        binding.ansUnitEnd.setText("季度");
                        break;
                    case "重量换算":
                        // ============= 换算前的单位设置 前后两个 =========================//
                        binding.preUnit.setText("吨");
                        binding.preUnitEnd.setText("t");

                        // ============= 换算后的单位设置 前后两个 =========================//
                        binding.ansUnit.setText("公斤");
                        binding.ansUnitEnd.setText("kg");
                }
                binding.resultDisplay.setText("0");
                binding.input.setText("0");
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


        //点击选择

        binding.preUnitWrapper.setOnClickListener(v -> {
            if (TextUtils.isEmpty(currentTab)) {
                Toast.makeText(requireContext(), "请选择tab标签", Toast.LENGTH_SHORT).show();
                return;
            }
//       List<String> mapData = units.get(currentTab).stream().map(UnitBean::getCn).collect(Collectors.toUnmodifiableList());
       List<UnitBean> mapData = units.get(currentTab).stream().collect(Collectors.toUnmodifiableList());

//            selectUnit2("前置选择", mapData);
            selectUnit("前置选择", mapData);
        });


        binding.ansUnitWrapper.setOnClickListener(v -> {
            if (TextUtils.isEmpty(currentTab)) {
                Toast.makeText(requireContext(), "请选择tab标签", Toast.LENGTH_SHORT).show();
                return;
            }
//            List<String> mapData = units.get(currentTab).stream().map(UnitBean::getCn).collect(Collectors.toUnmodifiableList());
            List<UnitBean> mapData = units.get(currentTab).stream().collect(Collectors.toUnmodifiableList());
            selectUnit("后置选择", mapData);
//            selectUnit2("后置选择", mapData);
        });
    }

    @SuppressLint("NewApi")
    private void initTabBar() {

        if (binding.tabWrapper.getTabCount() == 0) {
            binding.tabWrapper.removeAllTabs();
            tabs.clear();
            tabs.add("长度换算");
            tabs.add("体积换算");
            tabs.add("速度换算");
            tabs.add("时间换算");
            tabs.add("重量换算");

            tabs.stream().forEach(tabItem -> {
                binding.tabWrapper.addTab(binding.tabWrapper.newTab().setText(tabItem));
            });

            currentTab = tabs.get(0);
            binding.preUnit.setText("千米");
            binding.ansUnit.setText("米");
            binding.ansUnitEnd.setText("m");
            binding.preUnitEnd.setText("km");
        }


    }

    private void updateDisplay(View view, String value) {

    }

    @SuppressLint("SetTextI18n")
    private void observer() {
        viewModel.getResult().observe(getViewLifecycleOwner(), new Observer<BigDecimal>() {
            @Override
            public void onChanged(BigDecimal bigDecimal) {
                binding.resultDisplay.setText(bigDecimal.toString());
            }
        });

    }


    public void selectUnit(String tag, List<UnitBean> data) {

        UnitSelectInnerBinding unitSelectInnerBinding = UnitSelectInnerBinding.inflate(getLayoutInflater());
        unitSelectInnerBinding.selectUnitLabel.setText("sdsds");
        unitSelectInnerBinding.unitSelectList.setLayoutManager(new LinearLayoutManager(requireContext()));
        unitSelectInnerBinding.unitSelectList.setAdapter(new GasUnitSelectorAdapter(requireActivity() , R.layout.unit_select_item , data));
        BasePopupView custom = new XPopup.Builder(requireContext())
                .maxHeight(1000)
                .asCustom(new BasePopupView(requireContext()) {
                    @SuppressLint("NewApi")
                    @Override
                    protected int getInnerLayoutId() {
                        return unitSelectInnerBinding.getRoot().getSourceLayoutResId();
                    }
                });

        custom.show();
//        BottomListPopupView popupView = new XPopup.Builder(requireContext())
//                .maxHeight(1000)
//                .asBottomList("选择单位", data.toArray(new String[]{}), new OnSelectListener() {
//                    @Override
//                    public void onSelect(int position, String text) {
//                        queryResult(tag, text);
//                    }
//                });
//
//        popupView.setPadding(0, 0, 0, 40);
//        popupView.show();

    }

    public void selectUnit2(String tag, List<String> data) {
                BottomListPopupView popupView = new XPopup.Builder(requireContext())
                .maxHeight(1000)
                .asBottomList("选择单位", data.toArray(new String[]{}), new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        queryResult(tag, text);
                    }
                });

        popupView.setPadding(0, 0, 0, 40);
        popupView.show();
    }

    @SuppressLint("NewApi")
    @Override
    public void queryResult(String tag, String text) {
        List<UnitBean> unitBeans = units.get(currentTab);
        List<UnitBean> filterResult = unitBeans.stream().filter(item -> item.getCn().equals(text)).collect(Collectors.toUnmodifiableList());
        String zn = filterResult.get(0).getZn();
        String cn = filterResult.get(0).getCn();

        switch (tag) {
            case "前置选择":
                binding.preUnit.setText(cn);
                if (zn != null) {
                    binding.preUnitEnd.setText(zn);
                } else {
                    binding.preUnit.setText(text);
                }

                break;
            case "后置选择":
                binding.ansUnit.setText(cn);
                if (zn != null) {
                    binding.ansUnitEnd.setText(zn);
                }else {
                    binding.ansUnitEnd.setText(cn);
                }
                break;

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.input.setText("0");
        binding.resultDisplay.setText("0");
    }
}







